////
////  FinancialDetailVC.swift
////  HengYouCai
////
////  Created by lwj on 2017/11/10.
////  Copyright © 2017年 lwj. All rights reserved.


import UIKit
import WebKit

extension UIImage {
    // MARK: - 改变图片的颜色
    public func ss_imageWithTintColor(_ color: UIColor) -> UIImage? {
        return ss_image(color, blendMode: .destinationIn)
    }
    
    public func ss_imageWithGradientTintColor(_ color: UIColor) -> UIImage? {
        return ss_image(color, blendMode: .overlay)
    }
    
    private func ss_image(_ tintColor: UIColor, blendMode: CGBlendMode) -> UIImage? {
        // We want to keep alpha, set opaque to NO;
        // Use 0.0f for scale to use the scale factor of the device’s main screen.
        UIGraphicsBeginImageContextWithOptions(size, false, 0)
        
        tintColor.setFill()
        
        let bounds = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        
        UIRectFill(bounds)
        
        // Draw the tinted image in context
        draw(in: bounds, blendMode: blendMode, alpha: 1.0)
        
        if blendMode != .destinationIn {
            draw(in: bounds, blendMode: .destinationIn, alpha: 1.0)
        }
        
        let tintedImage = UIGraphicsGetImageFromCurrentImageContext()
        
        UIGraphicsEndImageContext()
        
        return tintedImage
    }
}
class FinancialDetailVC: BaseViewController,UITableViewDelegate,UITableViewDataSource{
    
    
    /// 列表
    var myTableView = UITableView()
    
    /// 详情数据模型
    var detailModel : DetailModel?
    
    /// 首页穿过来的模型数据
    public var homeModel = ProjectModel()
    
    /// 其他界面传过来的id
    var idStr  = String()
    /// 表头 高度
    //    var currentHeaderHeight : CGFloat = 338.0
    
    /// 表头
    var headerView = DetailHeaderView(frame: CGRect(x: 0, y: 0, width: JCWSCREENW, height: 300 + kJcwGetNavHeight()))
    
    /// 用于下拉的时候 判断 是否正在刷新中
    var noRefreshing = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.initMytableView()
        self.initNavigationBar()
        self.bottomView()
        self.loadData()
        
        weak var weakSelf = self
        let header = LWRefreshGifHeader(refreshingBlock: {
            weakSelf?.loadData()
        })
        header?.stateLabel.textColor = Color.white
        header?.lastUpdatedTimeLabel.textColor = Color.white
        header?.isAutomaticallyChangeAlpha = true
        header?.ignoredScrollViewContentInsetTop = -kJcwGetNavHeight()
        self.myTableView.mj_header = header
//        mj_head?.stateLabel.font = UIFont.systemFont(ofSize: 14)
//        // 设置刷新状态文本字体颜色
//        mj_head?.stateLabel.textColor = UIColor.red
        self.myTableView.bringSubview(toFront: header!)
        
        //顶部拉伸不为白色
        let bgLayer = CALayer()
        bgLayer.backgroundColor = ColorFromRGBHex_WL(0x3d3d3d).cgColor
        bgLayer.frame = CGRect(x: 0, y: -JCWSCREENH, width: JCWSCREENW, height: JCWSCREENH)
        self.myTableView.layer.insertSublayer(bgLayer, at: 0)
    }
    
    @objc private func pop() {
        navigationController?.popViewController(animated: true)
    }
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        ///导航条透明处理
        // 导航栏透明
        self.navigationController?.navigationBar.setBackgroundImage( UIImage(named: "touming"), for: UIBarMetrics.default)
        self.navigationController?.navigationBar.shadowImage = UIImage()
        let btn = UIButton()
        btn.setImage(UIImage(named: "back")?.ss_imageWithTintColor(UIColor.white), for: .normal)
        btn.addTarget(self, action: #selector(pop), for: .touchUpInside)
//        let leftItem = UIBarButtonItem(image:  UIImage(named: "back")?.ss_imageWithTintColor(UIColor.white), style: .plain, target: self, action: #selector(pop))
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)
//        self.navigationController?.navigationBar.backIndicatorImage =
        
        UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
        
        self.navigationController?.navigationBar.subviews.first?.alpha = 0
        
        ///投资完成返回之后跳转投资记录
        let isFinishInvest = UserDefaults.standard.bool(forKey: "isFinishInvest")
        if isFinishInvest {
            
            
            UserDefaults.standard.set(false, forKey: "isFinishInvest")
            
            let recordVC = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "InvestmentRecordVCID") as! InvestmentRecordVC
            recordVC.id = self.idStr
            self.navigationController?.pushViewController(recordVC, animated: false)
            
        }
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        // 返回按钮黑色
        self.navigationController?.navigationBar.backIndicatorImage = UIImage(named: "back")
        
    }
    func initNavigationBar() {
        
        let titleLab = UILabel()
        titleLab.font = Font_WL(16)
        titleLab.textColor = UIColor.white
        titleLab.text = homeModel.title
        titleLab.sizeToFit()
        self.navigationItem.titleView = titleLab
        
        // tableview自动下沉问题
        if #available(iOS 11.0, *) {
            
            self.myTableView.contentInsetAdjustmentBehavior = .never
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        //        self.navigationController?.navigationBar.shadowImage = nil
    }
    
    /// 投资按钮
    let investBtn = UIButton(type: UIButtonType.custom)
    
    /// 第一页的tableView
    func initMytableView() {
        
        let rect = CGRect(x: 0, y: 0, width: JCWSCREENW, height: JCWSCREENH - kJcwGetTabbarHeight())
        
        myTableView = UITableView(frame: rect, style: .plain)
        myTableView.backgroundColor = Normal_458Color
        myTableView.separatorStyle = .none
        
        myTableView.delegate = self
        myTableView.dataSource = self
        
        myTableView.tableHeaderView = self.headerView
        
        //        myTableView.tableFooterView = self.customTableFooterView
        myTableView.register(DetailCustomCell.self, forCellReuseIdentifier: "cellID")
        
        myTableView.estimatedRowHeight = 0
        myTableView.estimatedSectionFooterHeight = 0
        myTableView.estimatedSectionHeaderHeight = 0
        self.view.addSubview(myTableView)
    }
    
    /// 计算器和立即投资按钮
    func bottomView() {
        let bottomView = UIView()
        bottomView.backgroundColor = homeModel.status=="30" ? ColorFromRGBHex_WL(0xC1A057) : Normal_999Color
        self.view.addSubview(bottomView)
        _ = bottomView.sd_layout()
            .leftSpaceToView(self.view,0)?
            .rightSpaceToView(self.view,0)?
            .bottomSpaceToView(self.view,0)?
            .heightIs(kJcwGetTabbarHeight())
        
        /// 计算器下面的半透明View
        let bottomView2 = UIView()
        bottomView2.backgroundColor = homeModel.status=="30" ? ColorFromRGBHex_WL(0xccab62) : ColorFromRGBHex_WL(0xaaaaaa)
        bottomView.addSubview(bottomView2)
        _ = bottomView2.sd_layout()
            .topSpaceToView(bottomView,0)?
            .leftSpaceToView(bottomView,0)?
            .widthIs(49)?
            .heightIs(49)
        
        
        /// 计算器
        let calBtn = UIButton(type: UIButtonType.custom)
        calBtn.setImage(UIImage(named: "Details_cal"), for: .normal)
        bottomView.addSubview(calBtn)
        _ = calBtn.sd_layout()
            .topSpaceToView(bottomView,0)?
            .leftSpaceToView(bottomView,0)?
            .widthIs(64)?
            .heightIs(49)
        
        calBtn.rac_signal(for: UIControlEvents.touchUpInside).subscribeNext { (_) in
            
            if self.detailModel?.products != nil {
                let productModel : ProjectModel = (self.detailModel?.products)!
                
                let limitValue: String = productModel.plstimeLimitValue + (productModel.plstimeLimitType == "0" ? "天" : "个月")
                let profitStr = NSString(profit: productModel.minProfit)
                // 计算器view
                _ = CalculatorView(productModel.id, profitStr! as String, limitValue, model: self.detailModel)
            }
            
            
        }
        /// 投资按钮
//        let investBtn = UIButton(type: UIButtonType.custom)
        
        let titleStr :String =  NSString(status:self.homeModel.status) as String
//        investBtn.setTitle(titleStr, for: .normal)
        investBtn.setTitleColor(UIColor.white, for: .normal)
        investBtn.backgroundColor = ColorFromRGBHex_WL(0xC1A057)
//        investBtn.isEnabled = titleStr == "立即投资"
        investBtn.isEnabled = (homeModel.status=="30")
        investBtn.titleLabel?.font = Font_WL(14)
        bottomView.addSubview(investBtn)
        _ = investBtn.sd_layout()
            .topSpaceToView(bottomView,0)?
            .leftSpaceToView(calBtn,0)?
            .rightSpaceToView(bottomView,0)?
            .heightIs(49)
        
        weak var weakSelf = self
        investBtn.rac_signal(for: UIControlEvents.touchUpInside).subscribeNext { (_) in
            
            
            
            // 没登录
            if !isLogin(){
                self.present(LOGINVC(), animated: true, completion: nil)
                return
            }
            let pswWord = UserDefaults.standard.string(forKey: kUserPaypassword) ?? ""
            let realname = UserDefaults.standard.string(forKey: kRealnameStatus) ?? ""
            
            // 没有设置交易密码 或者是 没有 实名认证跳三部曲
            if pswWord.count < 1 || realname != "1"{
                
                let investPrepare = InvestPrepareVC()
                
                _ = JCWAccountTrilogyAlertView(headerImageNamed: nil, callBack: {
                    //
                    weakSelf?.navigationController?.pushViewController(investPrepare, animated: true)
                    
                })
                
            }else{
                
                let investVC = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "InvestmentConfirmVCID") as! InvestmentConfirmVC
                investVC.normalModel = weakSelf?.detailModel?.products
                weakSelf?.navigationController?.pushViewController(investVC, animated: true, withHideBottomBarWhenPush: true, pop: true)
            }
            
            
            
            
        }
    }
    
}

// MARK: - tableView的代理
extension FinancialDetailVC {
    
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            return indexPath.row == 3 ? 15 : 30
            
        }else{
            return 45
        }
    }
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            
            return  4
        }else{
            return 3
        }
        
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            if indexPath.row<3 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "cellID") as! DetailCustomCell
                
                
                
                
                cell.lineView.isHidden = indexPath.row==2
                cell.backgroundColor = UIColor.white
                let imgName : [String] = detailModel?.products.type == "0" ? ["Deatails_inter","Deatails_mode","Deatails_redpacket"] : ["Deatails_inter","Deatails_mode","Deatails_money"]
                var titleName : [String] = ["","",""]
                
                if detailModel?.products != nil {
                    if detailModel?.products.type == "0"{
//                        titleName = ["起息方式","还款方式","返现红包"]
                        titleName = [detailModel?.calInterestTypeLabel2 ?? "",
                                     detailModel?.repaymentTypeLabel2 ?? "",
                                     detailModel?.cashRateLabel2 ?? ""]
                    }else{
//                        titleName = ["起息方式","还款方式","剩余可投"]
                        titleName = [detailModel?.calInterestTypeLabel2 ?? "",
                                     detailModel?.repaymentTypeLabel2 ?? "",
                                     detailModel?.vipRuleLabel2 ?? ""]
                    }
                }
                
                cell.redIcon.image = UIImage(named: imgName[indexPath.row])
                cell.titleLab.text = titleName[indexPath.row]
                if indexPath.row == 0 {
                    cell.desLab.text = detailModel?.calInterestTypeLabel
                }
                if indexPath.row == 1 {
                    cell.desLab.text = detailModel?.repaymentTypeLabel
                }
                if indexPath.row == 2 {
                    if detailModel?.products.type == "0"{
                        
                        cell.desLab.text = detailModel?.cashRateLabel
                    }else{
                        cell.desLab.text = detailModel?.vipRuleLabel
                    }
                }
                return cell
                
            }else{
                
                let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
                cell.selectionStyle = .none
                return cell
                
            }
        }else{
            let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
            cell.selectionStyle = .default
            cell.accessoryView = UIImageView(image: UIImage(named:"safe_ringht"))
            
            cell.textLabel?.text = indexPath.row == 0 ? detailModel?.productsDetailsLabel : indexPath.row == 1 ? detailModel?.productsReportLabel : detailModel?.orderListLabel
            cell.textLabel?.font = Font_WL(14)
            cell.textLabel?.textColor = Normal_333Color
            if indexPath.row < 2 {
                let lineView = UIView(frame: CGRect(x: 15, y: 43.5, width: JCWSCREENW - 15, height: 0.5))
                lineView.backgroundColor = Normal_CCCColor
                cell.contentView.addSubview(lineView)
                
            }
            return cell
            
        }
        
        
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 1 {
            if indexPath.row == 0 {
                
                let bannerWebView = BannerWebViewVC(urlStr: JCW_ProductsDetails + self.idStr, title: detailModel?.productsDetailsLabel ?? "项目详情")
                //
                self.navigationController?.pushViewController(bannerWebView!, animated: true)
                
            }else if indexPath.row == 1 {
                let bannerWebView = BannerWebViewVC(urlStr:JCW_ProductsReport + self.idStr , title: detailModel?.productsReportLabel ?? "安全保障")
                //
                self.navigationController?.pushViewController(bannerWebView!, animated: true)
            }else{
                let recordVC = UIStoryboard(name: "Home", bundle: nil).instantiateViewController(withIdentifier: "InvestmentRecordVCID") as! InvestmentRecordVC
                recordVC.titleName = detailModel?.orderListLabel
                recordVC.id = self.idStr
                self.navigationController?.pushViewController(recordVC, animated: true)
                
            }
            
        }
        
        
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1{
            return 8
        }else{
            return 0.1
        }
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 1 {
            let headerView = UIView()
            headerView.backgroundColor = Normal_458Color
            return headerView
        }else{
            let headerView = UIView()
            headerView.backgroundColor = UIColor.white
            return headerView
        }
    }
    
    
}

// MARK: - 详情数据请求
extension FinancialDetailVC {
    fileprivate func loadData() {
        
        //        let idStr : String = self.homeModel.id
        
        
        HYCNetService.productsDetails(withDict: ["id":idStr], onSuccess: { (result) in
            //
            self.myTableView.mj_header?.endRefreshing()
            
            self.noRefreshing = true
            
            self.detailModel = DetailModel.mj_object(withKeyValues: result)
            
            self.headerView.setUpHeaderView(self.detailModel!)
            
            if let buttonStatus = self.detailModel?.buttonStatus {
                self.investBtn.isEnabled = buttonStatus
            }
            
            self.investBtn.setTitle(self.detailModel?.buttonLabel, for: .normal)
            
            self.myTableView.reloadData()
        }) { (code, errMsg) in
            //
            self.myTableView.mj_header?.endRefreshing()
            
            self.noRefreshing = true
        }
        
        
    }
}
